<template>
    <div>
        <Modal v-model="editRelatePeople" label-position="left" :mask-closable="false" width="1500" title="编辑角色关联人员">
            <div style="padding-bottom: 50px;">
                <!--<Form :model="editRelateFrom" :label-width="80">-->
                <div class="editModal float-left" style="width:1033px;">
                        <Table border :columns="prelistColumns" :data="prelistDatas"></Table>
                </div>
                    <div style="display: inline-block;margin-left:30px;width: 260px;vertical-align: top">
                        <Input v-model="args.search.userName" @keyup.up.native.prevent="up" @keyup.down.native.prevent="down" clearable autofocus placeholder="用户名/账户搜索"></Input>
                        <ul ref="ulList" style="margin-top: 10px;max-height: 450px;overflow-y: scroll;border: 1px solid #ccc;">
                            <li ref="searchResult" title="双击添加" @keyup.up.native="up" @keyup.down.native="down" @click="selIndex=index" @dblclick="addToLeft(index,item)" @keyup.enter.native.prevent="addToLeft(index, item)"
                                class="aa" :class="{aaa: selIndex===index}" v-for="(item,index) in searchTb.filter(item1 => !args.search.userName||item1.label.indexOf(args.search.userName)>-1)" :key="item.key" style="border-bottom: 1px solid #ccc;text-align: center;">
                                <span style="text-align:left;display:inline-block;width: 190px;padding: 0 10px">{{item.label}}</span>
                                <span style="display:inline-block;width: 40px;border-left: 1px solid #ccc"><Button type="text" @click="addToLeft(index,item)">+</Button></span>
                            </li>
                        </ul>
                </div>
                <!--<div class="float-right">
                    <div>
                        <Input v-model="value13">
                            <Select v-model="select3" slot="prepend" style="width: 80px">
                                <Option value="用户名">用户名</Option>
                                <Option value="账户">账户</Option>
                            </Select>
                            <Button slot="append" icon="ios-search"></Button>
                        </Input>
                    </div>
                </div>-->
                <div class="clear"></div>
                <Button type="primary" @click="truePeople" style="float:right;">保存</Button>
                <!--</Form>-->
            </div>
            <div slot="footer"></div>
        </Modal>
    </div>
</template>

<script type="text/ecmascript-6">
    import Vue from 'vue'
    import {editpeopleApi} from '../../../http/role.api'
    import * as employeeOpr from '../../../http/employee.api'
    import axios from 'axios'
    export default {
        name: 'editRelatePeople',
        props: {
            perInfo: {
                type: Object
            },
            prelistDatas: {
                type: Array
            }
        },
        data () {
            return {
                editRelateFrom: {},
                //搜索下拉框
                editRelatePeople:false,
                value13: '',
                select3: 'day',
                itemOpt: [],
                editRelateFrom:'',
                editRelateParams: {
                    /*employeeIds: [1,6]*/
                    employeeIds: []
                },
                // 角色key
                prelistColumns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {
                        title: '用户名',
                        width: 100,
                        key: 'employeeName',
                    },
                    {
                        title: '账户',
                        width: 100,
                        key: 'userName'
                    },
                    {
                        title: '部门',
                        width: 100,
                        key: 'orgStructId'
                    },
                    {
                        title: '状态',
                        width: 100,
                        key: 'status'
                    },
                    {
                        title: '联系方式',
                        width: 120,
                        key: 'contact'
                    },
                    {
                        title: '腾讯通',
                        width: 80,
                        key: 'rtx'
                    },
                    {
                        title: '邮箱',
                        width: 150,
                        key: 'email'
                    },
                    {
                        title: '创建时间',
                        width: 120,
                        key: 'createTime'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 100,
                        align: 'center',
                        render: (h, {row, index, column}) => {
                            const _this = this;
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small'
                                    },
                                    on: { // 编辑用户
                                        click: function () {
                                            _this.prelistDatas.splice(index, 1)
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                    employeeStatusOpts: [
                        {label: '正常', val: 'normal'},
                        {label: '禁用', val: 'forbidden'},
                        {label: '离职', val: 'disable'}
                    ],
                    employeeTbPage: {
                        current: 1,
                        total: 200,
                    },
                    searchTb: [],
                    args: { // 员工列表参数
                        search: {
                            userName: undefined,     //用户名
                            // employeeName: undefined, // 员工姓名
                            // status: undefined,       //员工状态
                            orgStructId: undefined,  //组织架构id
                        },
                        pageReqired: true,    // 分页 true 是 false 否
                        limit: 20,            // 每页数目
                        offset: 0,            // 偏移量
                        sort: 'createTime',   // 排序的字段
                        order: 'desc',        // asc 升序 desc 降序
                    },
                    employeeTbSelection: [],
                    relative_employees_columns: [
                        {
                            title: '用户名',
                            key: 'userName',
                            width: 100,
                            fixed: 'left',
                            sortable: true
                        }, {
                            title: '员工姓名',
                            key: 'employeeName',
                            width: 140
                        }, {
                            title: '性别',
                            key: 'gender',
                            width: 75,
                            render: function (h, {row, index, column}) {
                                const _self = this;
                                return h('span',{},[row[column.key]&&'男'||'女']);
                            }.bind(this),
                        }, {
                            title: '部门',
                            key: 'deptName',
                            width: 100
                        }, {
                            title: '职能',
                            key: 'duty',
                            width: 150
                        }, {
                            title: '状态',
                            key: 'status',
                            width: 75,
                            render: function (h, {row, index, column}) {
                                const _self = this;
                                let node = _self.employeeStatusOpts.find(item => item.val===row[column.key]);
                                return h('span',{style:{color: (row[column.key]==='normal')&&'#008000'||(row[column.key]==='forbidden')&&'#FF0000'}},[node&&node.label||'']);
                            }.bind(this),
                        }, {
                            title: '联系方式',
                            key: 'contact',
                            width: 120
                        }, {
                            title: '腾讯通',
                            key: 'rtx',
                            width: 100
                        }, {
                            title: '邮箱',
                            key: 'email',
                            width: 100
                        }, {
                            title: '创建时间',
                            key: 'createTime',
                            width: 100,
                            render: (h, {row, index, column}) => h('span',{},[(row[column.key]&&moment(row[column.key]).format('YYYY-MM-DDTHH:mm:ss')||'')]),
                        }, {
                            title: '操作',
                            fixed: 'right',
                            width: 80,
                            render: (h, {row, index, column}) => {
                                const _this = this;
                                return h('div', [
                                    h('Button', {
                                        props: {
                                            type: 'text',
                                            size: 'small'
                                        },
                                        on: { // 编辑用户
                                            click: function () {
                                                _this.prelistDatas.splice(index, 1)
                                            }
                                        }
                                    }, '删除')
                                ]);
                            }
                        }
                    ],
                    relative_employees_data: [],
                    selIndex: -1
                }
        },
        computed: {
            show: {// 控制当前模块显示关闭
                get() {
                    return this.$store.state.employee.showRelativeEmployeeModal
                },
                set(value) {
                    this.$store.commit('employee/toggleRelativeEmployeeModal', value)
                }
            },
        },
        watch: {
            'editRelatePeople' (val) {
                if (val) {
                   /* console.log("this.perInfo.id====="+this.perInfo.id)*/
                    this.editRelateFrom = JSON.parse(JSON.stringify(this.perInfo))
                }
            },
            show: function (newVal, oldVal) {
                if (newVal) {
                    const _this  = this;
                    // 初始化组织架构树
                    let args = Object.assign({}, _this.args)
                    let struct = _this.$store.state.employee.selectedOrgStruct
                    if (struct&&struct.node.origin.id) {
                        // args.search.orgStructId = struct.node.origin.id;// 这是浅拷贝有问题 目前不支持 ... 展开复制
                        args.search = Object.assign({}, {orgStructId: struct.node.origin.id})
                    }
                    _this.getList(args).then(function (res) {
                        _this.prelistDatas = res.data&&res.data.rows||[];
                    }).catch(function (err) {
                        console.log(err);
                    });
                    _this.getEmployeeNames()
                }
            }
        },
        mounted() {
            const _this = this;
            _this.$watch('args.search.userName', function (newVal, oldVal) {
                if (!newVal) {
                    _this.getEmployeeNames()
                    _this.selIndex = -1
                }
            })
        },
        created () {
            this.getEmployeeNames()
                    //this.getPerTable()
                    /*console.log(" selPer.row.id666==="+JSON.stringify(this.perInfo))*/
                    //人员列表
                    //editRelateApi (resp.data.rows.map(item => item.id),this.selPer).then(suc => {

                    //    console.log("suc"+suc)
                    //})
        },
        methods: {
            editList(){

            },
            truePeople () {
                console.log("this.editRelateParams6666==="+JSON.stringify(this.editRelateParams))

                this.editRelateParams.employeeIds = this.prelistDatas.map(item => (item.id))
                //编辑关联人员
                editpeopleApi(this.editRelateParams,this.editRelateFrom.id).then(suc => {
                    this.$emit('emitEditPerSuc')
                    this.editRelatePeople = false
                   /* this.spinShow = false*/
                }).catch(err => {
                    this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)
                   /*this.spinShow = false*/
                })
            },
            choose() { // 模态框确定
                const _this  = this;
                _this.$emit('employeeSelected', _this.prelistDatas);
            },
            addToLeft(index, item) {
                const _this = this;
                // 去重复 判断
                if (_this.prelistDatas.find(item2 => item2.userName===item.key)) {
                    return _this.$Message.warning('当前人员已存在，无需添加');
                }
                _this.getList({search:{userName: item.key}}).then(function (res) {
                    // _this.searchTb = res.data.rows;
                    if (res.data.rows&&res.data.rows.length) {
                        _this.searchTb.splice(index, 1)
                        _this.prelistDatas.push(res.data.rows[0])
                    } else {
                        console.log(res);
                    }
                }).catch(function (err) {
                    console.log(err);
                });

                // 设置分页信息
                // _this.employeeTbPage.total = _this.prelistDatas.length;
            },
            getList(args) {
                return employeeOpr.getEmployees(args).then(function (res) {
                    res.data && res.data.rows && res.data.rows.map(item => {
                        item.genderDesc = item.gender && '男' || '女'
                        // 关联角色
                        item.roleNames = item.roles && item.roles.map(role => role.roleName).join(',');
                        // 职能
                        item.duty = item.orgFuncs && item.orgFuncs.map(duty => duty.funcName).join(',');
                        // 部门
                        item.deptName = item.orgStruct && item.orgStruct.dept
                    });
                    return Promise.resolve(res);
                })
            },
            pageIndexChange(index) {
                this.args.offset = this.args.limit * (index - 1);
                this.employeeTbPage.current = index;
                // this.getEmployees();
            },
            pageSizeChange(size) {
                this.args.limit = size;
                this.args.offset = 0;
                this.employeeTbPage.current = 1; // 此时改变当前页会触发 pageIndexChange 查询
                // this.getEmployees();
            },
            getEmployeeNames(args) {
                const _this = this;
                employeeOpr.getEmployeeNames(args).then(function (res) {
                    const data = res.data.result;
                    _this.searchTb = Object.keys(data).map(key => ({key, label: `${key}-${data[key]||''}`}));
                }).catch(function (err) {
                    console.log(err)
                })
            },
            up(event) {
                this.selIndex = (this.$refs.searchResult.length+this.selIndex-1)%(this.$refs.searchResult.length)
            },
            down(event) {
                this.selIndex = (++this.selIndex)%(this.$refs.searchResult.length)
            }

        }
    }
</script>
<style>
    .float-left{
        float: left;
    }
    .float-right{
        float:right;
    }
    .clear{
        clear: both;
    }
    .aaa, .aa:hover, .aaa:focus {
        background: #eee;
    }
</style>